package com.jron.cqiu.kernel.implement.crossos.jnative;

import com.jron.cqiu.kernel.util.SingletonFactory;
import com.jron.cqiu.kernel.util.SingletonStrategy;
import com.jron.cqiu.kernel.cmdline.XP;
import com.jron.cqiu.util.ConfigurationUtil;
import com.jron.cqiu.util.FilePath;

import java.io.File;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Created by Intellij IDEA.
 *
 * @Author: Yejw
 * @Date: 2008-6-12
 * @Time: 21:42:29
 */
public class JNativeInit {

    private static Log log = LogFactory.getLog(JNativeInit.class);

    private static SingletonStrategy singleton = null;

    static String path = ConfigurationUtil.value("default.dll.path");
    static String file = ConfigurationUtil.value("jnative.dll.name");
    static String dest = path + File.separator + file;

    /**
     * JNative初始化实例
     *
     * @return
     */
    public static synchronized JNativeInit instance() {
        if (singleton == null)
            singleton = SingletonFactory.createSingleton("com.jron.cqiu.kernel.implement.crossos.jnative.JNativeInit");
        return (JNativeInit) singleton.instance();
    }

    public void init() {
        if (!isJNativeAvail()) {
            /*
            String source = FilePath.getFullPathRelateClass(ConfigurationUtil.value("jnative.ddl.pathexpress"),
                    JNativeInit.class) + File.separator + file;
            */
            String source = FilePath.getParentAbsolutePath("lib/" + file);
            if (!isFileExist(source)) {
                log.warn("The file: " + source + " is not exist!");
                source = FilePath.getParentAbsolutePath(file);
                if (!isFileExist(source)) {
                    log.warn("The file: " + source + " is not exist!");
                    return;
                } else log.warn("The file: " + source + " is found!");
            } else log.warn("The file: " + source + " is found!");
            XP.COPY.eval(source, StringUtils.substringBeforeLast(dest, "\\"));
        }
    }

    /**
     * 检查JNative组件是否可用
     *
     * @return
     */
    public static boolean isJNativeAvail() {
        return isFileExist(dest);
    }

    public static boolean isFileExist(String filePath) {
        File file = new File(filePath);
        try {
            return file.exists();
        } finally {
            file = null;
        }
    }
}
